import { useUserStore } from "@ui/vue/store";
import { getInstace } from "./local";
import { session } from "@ui/utils/temp";
let accessToken: string, getAccessTokenPromise: Promise<string> | undefined
export const MAGIC_SUCC_CODE: MagicResCode = 1, MAGIC_JQ_FAIL_CODE: MagicResCode = 101
export function magicGet(url: string, params: any = {}, data: any = {}) {
  return getInstace('magicApi').then(res => {
    return res.get(url, { data, params, headers: { accessToken } }).then((res: any) => {
      return res.data
    })
  })
}
export function magicPost<T>(url: string, data: any = {}, params: any = {}): Promise<MagicInterfaceRes<T>> {
  return getInstace('magicApi').then(res => {
    return res.post(url, data, { params, headers: { accessToken } }).then((res: any) => {
      return res.data
    })
  })
}
export function magicPostData<T>(url: string, data: any = {}, params: any = {}, rest: boolean = false): Promise<MagicInterfaceRes<T>> {
  const user = useUserStore().getUserInfo
  data = {
    data: {
      czryid: user.zhid,
      czryjgid: user.jgid,
      czryjgmc: user.jgmc,
      czryyhm: user.zh,
      czryxm: user.rxm,
      ...data
    }
  }
  return magicPost(url, data, params)
}
export function magicCheckAuth(rest: boolean = false): Promise<string> {
  accessToken = useUserStore().getUserToken
  if (rest || !(getAccessTokenPromise || accessToken)) {
    getAccessTokenPromise = (magicPost('magic/oauth/login', useUserStore().getUser) as Promise<any>).then((res: MagicJqRes) => {
      useUserStore().setUserInfo(res.data)
      session('user-token', accessToken)
      return accessToken = useUserStore().getUserToken
    })
  }
  return getAccessTokenPromise || Promise.resolve(accessToken)
}